package org.example.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.dto.MajorDto;
import org.example.service.MajorService;
import org.example.service.TestService;
import org.example.utils.JsonUtils;
import org.example.vo.MajorVo;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Rongchang Wu
 */
@RestController
public class MajorController {
    @Resource
    MajorService service;

    @GetMapping("/getMajorList")
    public void getMajorList(HttpServletResponse resp, Integer page, Integer limit) throws IOException {
        Page<Object> obj = PageHelper.startPage(page, limit);
        List<MajorDto> majorList = service.queryAllMajor();
        Integer count = service.countMajor();
        //以上调用service获取专业数据和数量

        JsonUtils.customJson(resp, majorList, count);
    }

    @GetMapping("/getMajorByDepartmentName")
    public void getMajorByDepartmentName(HttpServletResponse resp, String departmentName, Integer page, Integer limit) throws IOException {
        Page<Object> obj = PageHelper.startPage(page, limit);
        List<MajorDto> majorList = service.queryMajorByDepartmentName(departmentName);
        Integer count = service.countMajorByDepartment(departmentName);

        JsonUtils.customJson(resp, majorList, count);
    }

    @GetMapping(value = "/deleteMajor", produces = "text/plain;charset=utf-8")
    public String deleteMajor(String majorId) {
        String[] majorIds = majorId.split(",");
        Integer status = 0;
        for (int i = 0; i < majorIds.length; i++) {
            status += service.deleteMajor(Integer.parseInt(majorIds[i]));
        }

        return status > 0 ? "success" : "error";
    }

    @GetMapping(value = "/addMajor", produces = "text/plain;charset=utf-8")
    public String addMajor(MajorVo major) {
        Integer status = service.addMajor(major);

        return status > 0 ? "success" : "error";
    }

    @GetMapping(value = "/getMajorById")
    public MajorDto getMajorById(Integer majorId) {
        MajorDto major = service.queryMajorById(majorId);

        return major;
    }

    @GetMapping(value = "/editMajor")
    public String editMajor(MajorVo major) {
        Integer status = service.updateMajor(major);

        return status > 0 ? "success" : "error";
    }
}
